package com.foxit.mongodb;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.google.code.morphia.AdvancedDatastore;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.MongoClient;

public class DatastoreFactoryBean implements FactoryBean<AdvancedDatastore>, InitializingBean, DisposableBean{

	private Morphia morphia;    //morphia实例，最好是单例
	private MongoClient mongo;    //mongo实例，最好是单例
	private String dbName;    //数据库名
	private String username;    //用户名，可为空
	private String password;    //密码，可为空
	private boolean toEnsureIndexes = false;    //是否确认索引存在，默认false
	private boolean toEnsureCaps = false;    //是否确认caps存在，默认false   
	private AdvancedDatastore dataStore = null;
	
	public Morphia getMorphia() {
		return morphia;
	}

	public void setMorphia(Morphia morphia) {
		this.morphia = morphia;
	}

	public MongoClient getMongo() {
		return mongo;
	}

	public void setMongo(MongoClient mongo) {
		this.mongo = mongo;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isToEnsureIndexes() {
		return toEnsureIndexes;
	}

	public void setToEnsureIndexes(boolean toEnsureIndexes) {
		this.toEnsureIndexes = toEnsureIndexes;
	}

	public boolean isToEnsureCaps() {
		return toEnsureCaps;
	}

	public void setToEnsureCaps(boolean toEnsureCaps) {
		this.toEnsureCaps = toEnsureCaps;
	}

	public Datastore getDataStore() {
		return dataStore;
	}

	public void setDataStore(AdvancedDatastore dataStore) {
		this.dataStore = dataStore;
	}

	public void destroy() throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void afterPropertiesSet() throws Exception {
		// 这里的username和password可以为null，morphia对象会去处理
		AdvancedDatastore ds = (AdvancedDatastore) morphia.createDatastore(mongo, dbName, username,
				password == null ? null : password.toCharArray());
		if (toEnsureIndexes) {
			ds.ensureIndexes();
		}
		if (toEnsureCaps) {
			ds.ensureCaps();
		}
		this.dataStore = ds;
	}
	
	public AdvancedDatastore getObject() throws Exception {
		return this.dataStore;
	}
	
	public Class<?> getObjectType() {
		return Datastore.class;
	}
	
	public boolean isSingleton() {
		return true;
	}
}
